﻿using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class TileObjectPlane: MonoBehaviour, ILevelElementGUI, IPlayLevelElements, IExportReady
{
	delegate void EmptyVoid();
	public XMLData.Map.TileObject tileObject;
	
	bool isPlaying;
	Vector3 tmpPosition;
	
	platformScript _tmpPlatformScript;
	LadderScript _tmpLadderScript;
	chomperScript _tmpChomperScript;
	hiddenPlatButton _tmphiddenPlatBtnScript;
	MBDButtonScript _tmpMultiDoorButtonScript;
	MultiLockBWDoor _tmpMultiDoorScript;
	
	int tmpMultiID;
	List<int> multipleLinks;
	List<Transform>multipleLinkObj;
	bool isShowing;
	bool isTutorialOption;
	
	static int idGenerator = 0;
	static int maxId = 0;
	
	static readonly TILEOBJECTS[] LEVER_ALLOWED_TPYE = {TILEOBJECTS.LEVERDOOR};
	static readonly TILEOBJECTS[] BUTTON_ALLOWED_TPYE = {TILEOBJECTS.MOVEPLATFORM};
	static readonly TILEOBJECTS[] HIDDEN_PLATFORM_BTN_ALLOWED_TYPE = {TILEOBJECTS.HIDDENPLATFORM};
	static readonly TILEOBJECTS[] MULTI_LOCK_DOOR_ALLOWED_TYPE = {TILEOBJECTS.MULTILOCKDOORBTN};
	
	EmptyVoid guiHandler;
	
	public void ShowGUIElements ()
	{
		GUILayout.Box("ID:" + tileObject.ID.ToString().PadLeft(4, '0') + "-" + ((TILEOBJECTS)tileObject.objectType).ToString());
		if(guiHandler != null)
			guiHandler();
		
		GUILayout.BeginHorizontal();
		GUILayout.Box("IsLinked");
		GUILayout.Toggle(tileObject.isLinked, GUIContent.none);
		GUILayout.EndHorizontal();
		
		if(tileObject.isLinked)
		{
			if(multipleLinks == null)
			{
				GUILayout.BeginHorizontal();
				GUILayout.Box("Linked To:");
				GUILayout.Box(tileObject.linkedID.ToString());
				GUILayout.EndHorizontal();
			}
		}
		
		if(!tileObject.isLinked && GUILayout.Button("Delete"))
		{
			isShowing = false;
			int level = (gameObject.layer == LayerMask.NameToLayer("Player1Specific")? 1:2);
			LevelGrid.Instance.RemoveFromList(level, this);
			Destroy(gameObject);
		}
	}
	
	public void setObjectZPosition(float zPos)
	{
		Vector3 position = transform.position;
		position.z = zPos;
		position.y += 2;
		transform.position = position;
	}
	
	public void ReadyExport ()
	{
		if(tileObject.objectType == (int)TILEOBJECTS.MOVEPLATFORM)
		{
			GetComponent<platformScript>().isMoving =  isPlaying = false;
			transform.position = tmpPosition;
		}
	}
	public void Strip_Add_Components ()
	{
		if(tileObject.objectType == (int)TILEOBJECTS.MOVEPLATFORM)
		{
			RemoveComponent<BoxCollider>();
			GetComponent<platformScript>().setInfo(tileObject.platformInfo.fromPos, tileObject.platformInfo.toPos, tileObject.platformInfo.isX);
		}
		
		else if(tileObject.objectType == (int)TILEOBJECTS.LADDER || tileObject.objectType == (int)TILEOBJECTS.ROPE)
		{
			GetComponent<LadderScript>().setSize(tileObject.ladderSize);
		}
		
		else if(tileObject.objectType == (int)TILEOBJECTS.CHOMPER)
		{
			RemoveComponent<BoxCollider>();
			foreach(Transform tf in GetComponentInChildren<Transform>())
			{
				if(tf.collider != null)
					tf.collider.enabled = true;
			}
			GetComponent<chomperScript>().enabled = true;
			GetComponent<chomperScript>().timeCounter = tileObject.chomperCounter;
		}
		
		else if(tileObject.objectType == (int)TILEOBJECTS.HIDDENPLATFORM)
		{
			foreach(Transform tf in GetComponentInChildren<Transform>())
			{
				if(tf.renderer != null)
					tf.renderer.material.color = new Color(1,1,1,0);
			}
			RemoveComponent<BoxCollider>();
			int world = (gameObject.layer == LayerMask.NameToLayer("Player1Specific"))? 1: 2;
			Debug.Log("Setting Collider setup of:" + world);
			GetComponent<hiddenPlatformScript>().setColliderOffSet(world);
			staticTools.SetLayerRecursively(gameObject, 0);
			GetComponent<hiddenPlatformScript>().enabled = true;
		}
		
		else if(tileObject.objectType == (int)TILEOBJECTS.CHECKPOINT)
		{
			Vector3 position = transform.position;
			position.y += 2;
			transform.position = position;
			GetComponent<BoxCollider>().size = new Vector3(1,3,1);
			foreach(Transform tf in GetComponentInChildren<Transform>())
			{
				Destroy(tf.gameObject);
			}
		}
		
		else if(tileObject.objectType == (int)TILEOBJECTS.SPAWNPOINT)
		{
			BoxCollider bc = gameObject.GetComponent<BoxCollider>();
			Destroy(bc);
			foreach(Transform tf in GetComponentInChildren<Transform>())
			{
				Destroy(tf.gameObject);
			}
		}
		
		else if(tileObject.objectType == (int)TILEOBJECTS.TUTORIAL)
		{
			GetComponent<Renderer>().material.mainTexture = LevelAssetManager.Instance.getAsset<Texture2D>(KEYTYPE.TUTORIAL, tileObject.tutName);
			//Destroy(GetComponent<Collider>());
		}
		
		if(tileObject.isBothWorlds)
		{
			TILEOBJECTS tileType = (TILEOBJECTS)tileObject.objectType;
			if(tileType == TILEOBJECTS.KEY || tileType == TILEOBJECTS.PUSHBOX || tileType == TILEOBJECTS.KEYDOOR)
			{
				SetToBothWorld(true);
			}
		}
		RemoveComponent<TileObjectDrag>();
	}
	
	public XMLData.Map.TileObject Package()
	{
		tileObject.position = new XMLData.UnityObject.XMLVector3();
		tileObject.position.SetValue(transform.position);
		return tileObject;
	}
	
	public bool ToShow ()
	{
		return isShowing;
	}
	
	public int ObjectID
	{
		get{return tileObject.ID;}
	}
	
	public int ObjectType
	{
		get{return tileObject.objectType;}
	}
	
	public void RemoveComponent<T>() where T: Component
	{
		Destroy(gameObject.GetComponent<T>());
	}
	
	void Init(TILEOBJECTS type)
	{
		isShowing = true;
		tileObject = new XMLData.Map.TileObject();
		tileObject.objectType = (int)type;
		tileObject.ID = idGenerator;
		AssignSpecificHandler(type);
		idGenerator = idGenerator + 1;
	}
	
	void Init(XMLData.Map.TileObject tileObject)
	{
		isShowing = true;
		this.tileObject = tileObject;

		AssignSpecificHandler( (TILEOBJECTS)tileObject.objectType);
		
		//Find the biggest id
		if(tileObject.ID > maxId)
		{
			maxId = tileObject.ID;
			idGenerator = maxId + 2;
		}
	}
	
	#region LINKERS
	bool setLink(int LinkedID)
	{
		tileObject.isLinked = true;
		tileObject.linkedID = LinkedID;
		
		if(multipleLinks != null)
		{
			if(!multipleLinks.Contains(LinkedID))
			{
				multipleLinks.Add(LinkedID);
				return true;
			}
			return false;
		}
		return true;
	}
	
	public void addLink(int linkID, Transform tf)
	{
		multipleLinks.Add(linkID);
		multipleLinkObj.Add(tf);
	}
	
	void removeLink(int index)
	{
		if(_tmphiddenPlatBtnScript != null)
			_tmphiddenPlatBtnScript.platforms.Remove(multipleLinkObj[index].GetComponent<hiddenPlatformScript>());
		else if(_tmpMultiDoorScript != null)
			_tmpMultiDoorScript.myButtons.Remove(multipleLinkObj[index].GetComponent<MBDButtonScript>());
		
		multipleLinks.RemoveAt(index);
		multipleLinkObj.RemoveAt(index);
		if(multipleLinks.Count <= 0)
			tileObject.isLinked = false;
	}
	
	void deLink()
	{
		tileObject.isLinked = false;
		tileObject.linkedID = 0;
	}
	
	#endregion 
	
	void AssignSpecificHandler(TILEOBJECTS type)
	{
		if(type == TILEOBJECTS.LEVER)
			guiHandler = LeverGUIHandler;
		
		else if(type == TILEOBJECTS.GROUNDBTN)
		{
			guiHandler = GroundButtonGUIHandler;
		}
		
		else if(type == TILEOBJECTS.MOVEPLATFORM)
		{
			if(tileObject.platformInfo == null)
				tileObject.platformInfo = new XMLData.Map.PlatformInfo();
			
			_tmpPlatformScript = this.GetComponent<platformScript>();
			_tmpPlatformScript.setInfo(tileObject.platformInfo.fromPos, 
									   tileObject.platformInfo.toPos, 
									   tileObject.platformInfo.isX);
			guiHandler = PlatfromGUIHandler;
			tmpPosition = transform.position;
		}
		
		else if(type == TILEOBJECTS.LADDER || type == TILEOBJECTS.ROPE)
		{
			_tmpLadderScript = this.GetComponent<LadderScript>();
			_tmpLadderScript.setSize(tileObject.ladderSize);
			guiHandler = ClimbHandlerGUIHandler;
		}
		
		else if(type == TILEOBJECTS.CHOMPER)
		{
			foreach(Transform tf in GetComponentInChildren<Transform>())
			{
				if(tf.collider != null)
					tf.collider.enabled = false;
			}
			_tmpChomperScript = GetComponent<chomperScript>();
			_tmpChomperScript.enabled = false;
			guiHandler = ChomperGUIHandler;
		}
		
		else if(type == TILEOBJECTS.HIDDENPLATFORMBTN)
		{
			_tmphiddenPlatBtnScript = GetComponent<hiddenPlatButton>();
			multipleLinks = new List<int>();
			multipleLinkObj = new List<Transform>();
			guiHandler = HiddenPlatformGUIButton;
			
		}
		else if(type == TILEOBJECTS.HIDDENPLATFORM)
		{
			foreach(Transform tf in GetComponentInChildren<Transform>())
			{
				if(tf.renderer != null)
					tf.renderer.material.color = new Color(1,1,1,1);
			}
			gameObject.AddComponent<BoxCollider>();
			GetComponent<hiddenPlatformScript>().enabled = false;
		}
		
		else if(type == TILEOBJECTS.MULTILOCKDOOR)
		{
			_tmpMultiDoorScript = GetComponent<MultiLockBWDoor>();
			multipleLinks = new List<int>();
			multipleLinkObj = new List<Transform>();
			staticTools.SetLayerRecursively(gameObject, 0);
			guiHandler = MultiDoorGUIButton;
		}
		
		else if(type == TILEOBJECTS.TUTORIAL)
		{
			if(tileObject.tutName != null)
					GetComponent<Renderer>().material.mainTexture = LevelAssetManager.Instance.getAsset<Texture2D>(KEYTYPE.TUTORIAL, tileObject.tutName);
		}
		else if(type == TILEOBJECTS.KEY || type == TILEOBJECTS.PUSHBOX || type == TILEOBJECTS.KEYDOOR)
		{
			if(tileObject.isBothWorlds)
				SetToBothWorld(true);
			
			guiHandler = BothWorldGUIHandler;
		}
	}
	
	void SetLayerRecursively(int layerNumber)
    {
        foreach (Transform trans in  gameObject.GetComponentsInChildren<Transform>(true))
        {
            trans.gameObject.layer = layerNumber;
        }
    }
	
	void ChomperGUIHandler()
	{
		GUILayout.BeginHorizontal();
		GUILayout.Label("Chomper Counter:");
		tileObject.chomperCounter = float.Parse(GUILayout.TextField(tileObject.chomperCounter.ToString(), 4));
		GUILayout.EndHorizontal();
	}
	void LeverGUIHandler()
	{
		GUILayout.BeginHorizontal();
		if(!tileObject.isLinked)
		{
			GUILayout.Box("Link With:");
			tileObject.linkedID = int.Parse(GUILayout.TextField(tileObject.linkedID.ToString()));
			if(GUILayout.Button("Link"))
			{
				TileObjectPlane partnerPlane = LevelGrid.Instance.FindTilePlane(tileObject.linkedID);
				if(partnerPlane != null)
				{
					for(int i = 0; i < LEVER_ALLOWED_TPYE.Length; i++)
					{
						if(partnerPlane.ObjectType == (int)LEVER_ALLOWED_TPYE[i])
						{
							setLink(partnerPlane.ObjectID);
							GetComponent<leverScript>().partner = partnerPlane.GetComponent<blockScript>();
							partnerPlane.GetComponent<TileObjectPlane>().setLink(tileObject.ID);
						}
					}
				}
			}
		}
		
		else
		{
			if(GUILayout.Button("Remove Link"))
			{
				blockScript partner = GetComponent<leverScript>().partner;
				partner.GetComponent<TileObjectPlane>().deLink();
				GetComponent<leverScript>().partner = null;
				deLink();
			}
		}
		GUILayout.EndHorizontal();
	}
	
	void PlatfromGUIHandler()
	{
		GUILayout.BeginHorizontal();
		if(!isPlaying)
		{
			GUILayout.Label("IsXAxis");
			tileObject.platformInfo.isX = GUILayout.Toggle(tileObject.platformInfo.isX, GUIContent.none);
			
			GUILayout.Label("From:" );
			if(float.TryParse(GUILayout.TextField(tileObject.platformInfo.fromPos.ToString(),3), 
				System.Globalization.NumberStyles.AllowLeadingSign, null, 
				out tileObject.platformInfo.fromPos))
			{
				_tmpPlatformScript.setInfo(tileObject.platformInfo.fromPos, tileObject.platformInfo.toPos, tileObject.platformInfo.isX);
			}
			
			if(float.TryParse(GUILayout.TextField(tileObject.platformInfo.toPos.ToString(),3), 
				System.Globalization.NumberStyles.AllowLeadingSign, null, 
				out tileObject.platformInfo.toPos))
			{
				_tmpPlatformScript.setInfo(tileObject.platformInfo.fromPos, tileObject.platformInfo.toPos, tileObject.platformInfo.isX);
			}
			//tileObject.platformInfo.fromPos = float.Parse(GUILayout.TextField(tileObject.platformInfo.fromPos.ToString(),3), System.Globalization.NumberStyles.AllowLeadingSign);
		
			GUILayout.Label("To:" );
			//tileObject.platformInfo.toPos =   float.Parse(GUILayout.TextField(tileObject.platformInfo.toPos.ToString(), 3),System.Globalization.NumberStyles.AllowLeadingSign);
			
			if(GUILayout.Button("Play"))
			{
				GetComponent<platformScript>().isMoving =  isPlaying = true;
				tmpPosition = transform.position;
			}
			tmpPosition = transform.position;
		}
		
		else
		{
			if(GUILayout.Button("Stop"))
			{
				GetComponent<platformScript>().isMoving =  isPlaying = false;
				transform.position = tmpPosition;
			}
		}
		GUILayout.EndHorizontal();
	}
	
	void GroundButtonGUIHandler()
	{	
		GUILayout.BeginHorizontal();
		if(!tileObject.isLinked)
		{
			GUILayout.Box("Link With:");
			tileObject.linkedID = int.Parse(GUILayout.TextField(tileObject.linkedID.ToString()));
			if(GUILayout.Button("Link"))
			{
				TileObjectPlane tilePlane = LevelGrid.Instance.FindTilePlane(tileObject.linkedID);
				if(tilePlane != null)
				{
					for(int i = 0; i < BUTTON_ALLOWED_TPYE.Length; i++)
					{
						if(tilePlane.ObjectType == (int)BUTTON_ALLOWED_TPYE[i])
						{
							setLink(tilePlane.ObjectID);
							GetComponent<stepOnButScript>().partner = tilePlane.GetComponent<platformScript>();
							tilePlane.GetComponent<TileObjectPlane>().setLink(tileObject.ID);
						}
					}
				}
			}
		}
		
		else
		{
			if(GUILayout.Button("Remove Link"))
			{
				platformScript partner = GetComponent<stepOnButScript>().partner;
				partner.GetComponent<TileObjectPlane>().deLink();
				GetComponent<stepOnButScript>().partner = null;
				deLink();
			}
		}
		GUILayout.EndHorizontal();
	}
	
	void ClimbHandlerGUIHandler()
	{
		GUILayout.BeginHorizontal();
		GUILayout.Label("Height: ");
		tileObject.ladderSize = (int)GUILayout.HorizontalSlider(tileObject.ladderSize, 3,20);
		_tmpLadderScript.setSize(tileObject.ladderSize);
		GUILayout.EndHorizontal();
	}
	
	void HiddenPlatformGUIButton()
	{
		//Link
		GUILayout.BeginHorizontal();
		GUILayout.Label("Link With:");
		tmpMultiID = int.Parse(GUILayout.TextField(tmpMultiID.ToString()));
		if(GUILayout.Button("Link"))
		{
			TileObjectPlane tilePlane = LevelGrid.Instance.FindTilePlane(tmpMultiID);
			if(tilePlane != null)
			{
				for(int i = 0; i < HIDDEN_PLATFORM_BTN_ALLOWED_TYPE.Length; i++)
				{
					if(tilePlane.ObjectType == (int)HIDDEN_PLATFORM_BTN_ALLOWED_TYPE[i])
					{
						if(setLink(tilePlane.ObjectID))
						{
							multipleLinkObj.Add(tilePlane.transform);
							hiddenPlatformScript _hiddenPlatformScript = tilePlane.GetComponent<hiddenPlatformScript>();
							_hiddenPlatformScript.motherButton = _tmphiddenPlatBtnScript;
							_tmphiddenPlatBtnScript.platforms.Add(_hiddenPlatformScript);
							tilePlane.GetComponent<TileObjectPlane>().setLink(tileObject.ID);
						}
					}
				}
			}
		}	
		GUILayout.EndHorizontal();
		
		for(int i =0;  i < multipleLinks.Count; i++)
		{
			GUILayout.BeginHorizontal();
			GUILayout.Box("Linked To:");
			GUILayout.Box(multipleLinks[i].ToString());
			if(GUILayout.Button("Remove Link"))
			{
				hiddenPlatformScript _tmpPlatScript = multipleLinkObj[i].GetComponent<hiddenPlatformScript>();
				_tmpPlatScript.motherButton = null;
				_tmpPlatScript.GetComponent<TileObjectPlane>().deLink();
				removeLink(i);
			}
			GUILayout.EndHorizontal();
		}
	}
	
	void MultiDoorGUIButton()
	{
		//Link
		GUILayout.BeginHorizontal();
		GUILayout.Label("Link With:");
		tmpMultiID = int.Parse(GUILayout.TextField(tmpMultiID.ToString()));
		if(GUILayout.Button("Link"))
		{
			TileObjectPlane tilePlane = LevelGrid.Instance.FindTilePlane(tmpMultiID);
			if(tilePlane != null)
			{
				for(int i = 0; i < MULTI_LOCK_DOOR_ALLOWED_TYPE.Length; i++)
				{
					if(tilePlane.ObjectType == (int)MULTI_LOCK_DOOR_ALLOWED_TYPE[i])
					{
						if(setLink(tilePlane.ObjectID))
						{
							multipleLinkObj.Add(tilePlane.transform);
							MBDButtonScript _mbdScript = tilePlane.GetComponent<MBDButtonScript>();
							_mbdScript.myDoor = _tmpMultiDoorScript;
							_tmpMultiDoorScript.myButtons.Add(_mbdScript);
							tilePlane.GetComponent<TileObjectPlane>().setLink(tileObject.ID);
						}
					}
				}
			}
		}	
		GUILayout.EndHorizontal();
		
		for(int i =0;  i < multipleLinks.Count; i++)
		{
			GUILayout.BeginHorizontal();
			GUILayout.Box("Linked To:");
			GUILayout.Box(multipleLinks[i].ToString());
			if(GUILayout.Button("Remove Link"))
			{
				MBDButtonScript _tmpPlatScript = multipleLinkObj[i].GetComponent<MBDButtonScript>();
				_tmpPlatScript.myDoor = null;
				_tmpPlatScript.GetComponent<TileObjectPlane>().deLink();
				removeLink(i);
			}
			GUILayout.EndHorizontal();
		}
	}
	
	void BothWorldGUIHandler()
	{
		GUILayout.BeginHorizontal();
		GUILayout.Box ("OnBothWorld:");
		tileObject.isBothWorlds = GUILayout.Toggle(tileObject.isBothWorlds, GUIContent.none);
		SetToBothWorld(tileObject.isBothWorlds);
		GUILayout.EndHorizontal();
	}
	
	/*
	void TutorialGUIHandler()
	{
		if(GUILayout.Button("ChoosePicture"))
		{
			isTutorialOption = true;
		}
		//GUILayout.EndArea();
		if(isTutorialOption)
		{
			Debug.Log("SHowing tutorial Option");
			GUI.BeginGroup(new Rect(Screen.width * 0.25f, Screen.height * 0.25f, Screen.width * 0.25f, Screen.height * 0.5f));
			int chosen = -1;
			Texture2D[] selGrid = new Texture2D[5];
			chosen = GUI.SelectionGrid(new Rect(0,0, Screen.width, Screen.height),chosen, LevelAssetManager.Instance.GetAllAsset<Texture>(KEYTYPE.TUTORIAL), 5); 
			if(chosen != -1)
			{
				isTutorialOption = false;
				chosen = -1;
			}
			GUI.EndGroup();
		}
	}*/
	void SetToBothWorld(bool isBothWorld)
	{
		if(tileObject.isBothWorlds)
		{
			if(gameObject.layer != 0)
			{
				staticTools.SetLayerRecursively(gameObject, 0);
				GetComponent<BoxCollider>().size += new Vector3(0,0 ,10);
				foreach(Transform tf in GetComponentInChildren<Transform>())
				{
					MeshCollider mc = tf.GetComponent<MeshCollider>();
					if(mc != null)
					{
						tf.localScale += new Vector3(0, 0, 10.0f);
					}
					
					Renderer rend = tf.GetComponent<Renderer>();
					if(rend != null && rend.name != "particlegreen")
					{
						if((TILEOBJECTS)tileObject.objectType != TILEOBJECTS.KEYDOOR)
						{
							Texture txt = rend.material.mainTexture;
							rend.material =  LevelAssetManager.Instance.getAsset<Material>(KEYTYPE.MATERIAL, "CustomGreen");
							rend.material.mainTexture = txt;
						}
					}
					
					ParticleSystem ps = tf.GetComponent<ParticleSystem>();
					if(ps != null)
					{
						ps.gameObject.SetActive(true);
					}
				}
				
			}
		}
		else
		{
			if(gameObject.layer == 0)
			{
				staticTools.SetLayerRecursively(gameObject, LevelGrid.Instance.CurrentWorldMask);
				GetComponent<BoxCollider>().size -= new Vector3(0,0 ,10);
				foreach(Transform tf in GetComponentInChildren<Transform>())
				{
					MeshCollider mc = tf.GetComponent<MeshCollider>();
					if(mc != null)
					{
						tf.localScale -= new Vector3(0, 0, 10);
					}
					
					Renderer rend = tf.GetComponent<Renderer>();
					if(rend != null && rend.name != "particlegreen")
					{
						Texture txt = rend.material.mainTexture;
						rend.material =  LevelAssetManager.Instance.getAsset<Material>(KEYTYPE.MATERIAL, "CellMat");
						rend.material.mainTexture = txt;
					}
					
					ParticleSystem ps = tf.GetComponent<ParticleSystem>();
					if(ps != null)
					{
						ps.gameObject.SetActive(false);
					}
				}
			}
		}
	}
	
	#region TILEOBJECT CREATION PROCESS
	static TILEOBJECTS StringToObjType(string imgName)
	{
		if(imgName.ToLower().Contains("lvdoor"))
			return TILEOBJECTS.LEVERDOOR;
		
		else if(imgName.ToLower().Contains("lever"))
			return TILEOBJECTS.LEVER;
		
		else if(imgName.ToLower().Contains("ladder"))
			return TILEOBJECTS.LADDER;
		
		else if(imgName.ToLower().Contains("spike"))
			return TILEOBJECTS.SPIKE;
		
		else if(imgName.ToLower().Contains("mvplatbtn"))
			return TILEOBJECTS.GROUNDBTN;
		
		else if(imgName.ToLower().Contains("mvplat"))
			return TILEOBJECTS.MOVEPLATFORM;
		
		else if(imgName.ToLower().Contains("key"))
			return TILEOBJECTS.KEY;
		
		else if(imgName.ToLower().Contains("kydoor"))
			return TILEOBJECTS.KEYDOOR;
		
		else if(imgName.ToLower().Contains("box"))
			return TILEOBJECTS.PUSHBOX;
		
		else if(imgName.ToLower().Contains("rope"))
			return TILEOBJECTS.ROPE;
		
		else if(imgName.ToLower().Contains("chomp"))
			return TILEOBJECTS.CHOMPER;
		
		else if(imgName.ToLower().Contains("hideplatform"))
			return TILEOBJECTS.HIDDENPLATFORM;
		
		else if(imgName.ToLower().Contains("hideplatbtn"))
			return TILEOBJECTS.HIDDENPLATFORMBTN;
		
		else if(imgName.ToLower().Contains("multidoor"))
			return TILEOBJECTS.MULTILOCKDOOR;
		
		else if(imgName.ToLower().Contains("mdoorbtn"))
			return TILEOBJECTS.MULTILOCKDOORBTN;
		
		else if(imgName.ToLower().Contains("chkpt"))
			return TILEOBJECTS.CHECKPOINT;
		
		else if(imgName.ToLower().Contains("goal"))
			return TILEOBJECTS.GOAL;
		
		else if(imgName.ToLower().Contains("tut"))
			return TILEOBJECTS.TUTORIAL;
		
		else if(imgName.ToLower().Contains("spwnpt"))
			return TILEOBJECTS.SPAWNPOINT;
		
		return TILEOBJECTS.SPIKE;
	}
	
	public static GameObject GetTileObject(TILEOBJECTS type)
	{
		GameObject go = null;
		switch(type)
		{
		case TILEOBJECTS.LEVERDOOR:
			go = Network.Instantiate(LevelManager.Instance.LeverDoorPrefab, Vector3.zero, 
									 LevelManager.Instance.LeverDoorPrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.LEVER:
			go = Network.Instantiate(LevelManager.Instance.LeverPrefab, Vector3.zero, 
							 		 LevelManager.Instance.LeverPrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.MOVEPLATFORM:
			go = Network.Instantiate(LevelManager.Instance.MovingPlatform, Vector3.zero, 
									 LevelManager.Instance.MovingPlatform.transform.rotation,0) as GameObject;
			break;
			
		case TILEOBJECTS.SPIKE:
			go = Network.Instantiate(LevelManager.Instance.SpikePrefab, Vector3.zero, 
									 LevelManager.Instance.SpikePrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.GROUNDBTN:
			go = Network.Instantiate(LevelManager.Instance.GroundButton, Vector3.zero,
									 LevelManager.Instance.GroundButton.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.KEY:
			go = Network.Instantiate(LevelManager.Instance.KeyPrefab, Vector3.zero,
									 LevelManager.Instance.KeyPrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.KEYDOOR:
			go = Network.Instantiate(LevelManager.Instance.KeyDoorPrefab, Vector3.zero,
									 LevelManager.Instance.KeyDoorPrefab.transform.rotation, 0) as GameObject;
			break;
		
		case TILEOBJECTS.PUSHBOX:
			go = Network.Instantiate(LevelManager.Instance.PushBoxPrefab, Vector3.zero,
									 LevelManager.Instance.PushBoxPrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.LADDER:
			go = Network.Instantiate(LevelManager.Instance.LadderPrefab, Vector3.zero,
									 LevelManager.Instance.LadderPrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.ROPE:
			go = Network.Instantiate(LevelManager.Instance.RopePrefab, Vector3.zero,
									 LevelManager.Instance.RopePrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.CHOMPER:
			go = Network.Instantiate(LevelManager.Instance.ChomperPrefab, Vector3.zero,
									 LevelManager.Instance.ChomperPrefab.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.HIDDENPLATFORM:
			go = Network.Instantiate(LevelManager.Instance.HiddenPlatform, Vector3.zero,
									 LevelManager.Instance.HiddenPlatform.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.HIDDENPLATFORMBTN:
			go = Network.Instantiate(LevelManager.Instance.HiddenPlatformBTN, Vector3.zero,
									 LevelManager.Instance.HiddenPlatformBTN.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.MULTILOCKDOOR:
			go = Network.Instantiate(LevelManager.Instance.MultiLockDoor, Vector3.zero,
									 LevelManager.Instance.MultiLockDoor.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.MULTILOCKDOORBTN:
			go = Network.Instantiate(LevelManager.Instance.MultilockDoorButton, Vector3.zero,
									 LevelManager.Instance.MultilockDoorButton.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.CHECKPOINT:
			go = Network.Instantiate(LevelManager.Instance.CheckPoint, Vector3.zero,
									 LevelManager.Instance.CheckPoint.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.GOAL:
			go = Network.Instantiate(LevelManager.Instance.Goal, Vector3.zero,
									 LevelManager.Instance.Goal.transform.rotation, 0) as GameObject;
			break;
			
		case TILEOBJECTS.TUTORIAL:
			go = Network.Instantiate(LevelManager.Instance.Tutorial, Vector3.zero,
									 LevelManager.Instance.Tutorial.transform.rotation, 0) as GameObject;
			break;
		case TILEOBJECTS.SPAWNPOINT:
			go = Network.Instantiate(LevelManager.Instance.SpawnPoint, Vector3.zero,
									 LevelManager.Instance.SpawnPoint.transform.rotation, 0) as GameObject;
			break;
			
		}
		return go;
	}
	
	public static GameObject GetTileObjectLevel(TILEOBJECTS type)
	{
		GameObject go = null;
		switch(type)
		{
		case TILEOBJECTS.LEVERDOOR:
			go = Instantiate(LevelManager.Instance.LeverDoorPrefab) as GameObject;
			break;
			
		case TILEOBJECTS.LEVER:
			go = Instantiate(LevelManager.Instance.LeverPrefab) as GameObject;
			break;
			
		case TILEOBJECTS.MOVEPLATFORM:
			go = Instantiate(LevelManager.Instance.MovingPlatform) as GameObject;
			go.AddComponent<BoxCollider>();
			break;
			
		case TILEOBJECTS.SPIKE:
			go = Instantiate(LevelManager.Instance.SpikePrefab) as GameObject;
			break;
			
		case TILEOBJECTS.GROUNDBTN:
			go = Instantiate(LevelManager.Instance.GroundButton) as GameObject;
			break;
			
		case TILEOBJECTS.KEY:
			go = Instantiate(LevelManager.Instance.KeyPrefab) as GameObject;
			break;
			
		case TILEOBJECTS.KEYDOOR:
			go = Instantiate(LevelManager.Instance.KeyDoorPrefab) as GameObject;
			break;
		
		case TILEOBJECTS.PUSHBOX:
			go = Instantiate(LevelManager.Instance.PushBoxPrefab) as GameObject;
			break;
		case TILEOBJECTS.LADDER:
			go = Instantiate(LevelManager.Instance.LadderPrefab) as GameObject;
			break;
			
		case TILEOBJECTS.ROPE:
			go = Instantiate(LevelManager.Instance.RopePrefab) as GameObject;
			break;
		
		case TILEOBJECTS.CHOMPER:
			go = Instantiate(LevelManager.Instance.ChomperPrefab) as GameObject;
			go.AddComponent<BoxCollider>();
			break;
			
		case TILEOBJECTS.HIDDENPLATFORM:
			go = Instantiate(LevelManager.Instance.HiddenPlatform) as GameObject;
			break;
			
		case TILEOBJECTS.HIDDENPLATFORMBTN:
			go = Instantiate(LevelManager.Instance.HiddenPlatformBTN) as GameObject;
			break;
			
		case TILEOBJECTS.MULTILOCKDOOR:
			go = Instantiate(LevelManager.Instance.MultiLockDoor) as GameObject;
			break;
			
		case TILEOBJECTS.MULTILOCKDOORBTN:
			go = Instantiate(LevelManager.Instance.MultilockDoorButton) as GameObject;
			break;
			
		case TILEOBJECTS.CHECKPOINT:
			go = Instantiate(LevelManager.Instance.CheckPoint) as GameObject;
			break;
			
		case TILEOBJECTS.GOAL:
			go = Instantiate(LevelManager.Instance.Goal) as GameObject;
			break;
		
		case TILEOBJECTS.TUTORIAL:
			go = Instantiate(LevelManager.Instance.Tutorial) as GameObject;
			break;
		
		case TILEOBJECTS.SPAWNPOINT:
			go = Instantiate(LevelManager.Instance.SpawnPoint) as GameObject;
			break;
		}
		return go;
	}
	
	#endregion
	
	public static void ResetIDGenerator()
	{
		maxId = 0;
		idGenerator = 0;
	}
	
	public static TileObjectPlane Create(string imageName)
	{
		TILEOBJECTS type = StringToObjType(imageName);
		GameObject go = GetTileObjectLevel(type);
		TileObjectPlane tilePlane  = go.AddComponent<TileObjectPlane>();
		tilePlane.SetLayerRecursively(LevelGrid.Instance.CurrentWorldMask);
		Vector3 position = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 20));
		tilePlane.transform.position = position;
		tilePlane.gameObject.AddComponent<TileObjectDrag>();
		tilePlane.Init(type);
		return tilePlane;
	}
	
	public static TileObjectPlane Create(GameObject go, XMLData.Map.TileObject tileObject, int worldMask)
	{
		TileObjectPlane tilePlane = go.AddComponent<TileObjectPlane>();
		tilePlane.SetLayerRecursively(worldMask);
		tilePlane.transform.position = new Vector3(tileObject.position.x, tileObject.position.y, tileObject.position.z);
		tilePlane.gameObject.AddComponent<TileObjectDrag>();
		tilePlane.Init(tileObject);
		return tilePlane;
	}
}
	/*
public class TileObjectPlane : Plane2D , ILevelElementGUI
{
	XMLData.Map.TileObject tileObject;
	CellGrid[] affectedGrids;
	static uint ID = 0;
	static Vector2 scrollPos = Vector2.zero;
	
	TileObjectPlane(string planeName, 
				    Layer2D layer2D, 
				    int xLength, int yLength, int type):base(planeName, layer2D, true)
	{
		affectedGrids = new CellGrid[xLength * yLength];
		tileObject = new XMLData.Map.TileObject();
		tileObject.XLength = xLength;
		tileObject.YLength = yLength;
		tileObject.objectType = type;
		ID++;
	}
	
	public void ShowGUIElements ()
	{
		GUILayout.BeginScrollView(scrollPos, false, true);
		GUILayout.Label("ID:" + ID.ToString().PadLeft(4, '0'));
		
		GUILayout.EndScrollView();
	}
	
	public bool ToShow ()
	{
		return true;
	}
	
	public void lockCellGrids(CellGrid cellGrid)
	{
		int count = 0;
		LevelGrid lg = LevelGrid.Instance;
		GameObject[,] world  = (layer2D.MaskLayer == LayerMask.NameToLayer("world1"))? lg.World1: lg.World2;
		int originX = cellGrid.gridPosX;
		int originY = cellGrid.gridPosY;
		
		for(int y = 0; y < tileObject.YLength ; y++)
		{
			for(int x =0; x < tileObject.XLength; x++)
			{
				CellGrid cg = affectedGrids[count] = world[originX + x, originY + y].GetComponent<CellGrid>();
				cg.lockedByTile = this;
				cg.isLocked = true;
				count++;
			}
		}
	}
	
	static TileObjectPlane doorHandler(Layer2D layer2D)
	{
		TileObjectPlane tilePlane = new TileObjectPlane("DoorObject", layer2D, 3, 4, (int)TILEOBJECTS.DOOR);
		tilePlane.SetScale(new Vector2(3,4));
		return tilePlane;
	}
	
	static TileObjectPlane leverHandler(Layer2D layer2D)
	{
		TileObjectPlane tilePlane = new TileObjectPlane("LeverObject", layer2D, 1, 1, (int)TILEOBJECTS.LEVER);
		return tilePlane;
	}
	
	static TileObjectPlane ladderHandler(Layer2D layer2D)
	{
		TileObjectPlane tilePlane = new TileObjectPlane("LadderObject", layer2D, 1, 3, (int)TILEOBJECTS.LADDER);
		tilePlane.SetScale(new Vector2(1,3));
		return tilePlane;
	}
	
	static TileObjectPlane movingPlatform(Layer2D layer2D)
	{
		TileObjectPlane tilePlane = new TileObjectPlane("MovingPlatObject", layer2D, 3, 1, (int)TILEOBJECTS.MOVEPLATFORM);
		tilePlane.SetScale(new Vector2(3,1));
		return tilePlane;
	}
	
	public static TileObjectPlane Create(Texture2D image, Layer2D layer2D)
	{
		string imgName = image.name.ToLower();
		
		TileObjectPlane tilePlane = null;
		if(imgName.Contains("door"))
			tilePlane = doorHandler(layer2D);
		
		else if(imgName.Contains("lever") ||imgName.Contains("spikes"))
			tilePlane = leverHandler(layer2D);
		
		else if(imgName.Contains("ladder"))
		{
			tilePlane = ladderHandler(layer2D);
		}
		
		else if(imgName.Contains("plat"))
			tilePlane = movingPlatform(layer2D);
		
		
		tilePlane.SetImage(KEYTYPE.OBJECTS, image);
	
		return tilePlane;
	}
	
	public static TileObjectPlane Create(XMLData.Map.TileObject tileObject, Layer2D layer2D)
	{
		TileObjectPlane tilePlane = null;
		
		if(tileObject.objectType == (int)TILEOBJECTS.DOOR)
			tilePlane = doorHandler(layer2D);
		else if(tileObject.objectType == (int)TILEOBJECTS.LEVER)
			tilePlane = leverHandler(layer2D);
		else if(tileObject.objectType == (int)TILEOBJECTS.LADDER)
			tilePlane = ladderHandler(layer2D);
		else if(tileObject.objectType == (int)TILEOBJECTS.MOVEPLATFORM)
			tilePlane = movingPlatform(layer2D);
		
		XMLData.Map.Plane2DInfo plane2DInfo = tileObject.plane2D;
		LevelGrid lg = LevelGrid.Instance;
		GameObject[,] world  = (layer2D.MaskLayer == LayerMask.NameToLayer("world1"))? lg.World1: lg.World2;
		tilePlane.Load(plane2DInfo);
		
		CellGrid cg = world[tileObject.originTile.gridPosX, tileObject.originTile.gridPosY].GetComponent<CellGrid>();
		cg.lockedByTile = tilePlane;
		tilePlane.lockCellGrids(cg);
		layer2D.AddPlane2D(tilePlane);
		
		return tilePlane;
	}
	static public void RemoveOnCurrentObject()
	{
		LevelGrid.Instance.IsTileObject = false;
		//LevelGrid.Instance.CurrentTileObject = null;
	}
	
	public bool isPossible(CellGrid cellGrid)
	{
		LevelGrid lg = LevelGrid.Instance;
		GridSize size = lg.gridSize;
		int xLength = tileObject.XLength; 
		int yLength = tileObject.YLength;
		GameObject[,] world  = (layer2D.MaskLayer == LayerMask.NameToLayer("world1"))? lg.World1: lg.World2;
		
		int originX = cellGrid.gridPosX;
		int originY = cellGrid.gridPosY;
		
		for(int y = 0; y < tileObject.YLength ; y++)
		{
			for(int x =0; x < tileObject.XLength; x++)
			{
				CellGrid cg = world[originX + x, originY + y].GetComponent<CellGrid>();
				
				if(cg.isLocked)
					return false;
			}
		}
		if((cellGrid.gridPosX + xLength) > (size.X - 1) || (cellGrid.gridPosY + yLength) > (size.Y -1) )
			return false;
		
		return true;
	}
	
	public new XMLData.Map.TileObject Package()
	{
		XMLData.Map.TileObject _tileObject = new XMLData.Map.TileObject();
		XMLData.Map.Plane2DInfo plane2D = base.Package();
		_tileObject.plane2D = plane2D;
		_tileObject.XLength = tileObject.XLength;
		_tileObject.YLength = tileObject.YLength;
		_tileObject.objectType = tileObject.objectType;
		
		CellGrid cg = affectedGrids[0];
		_tileObject.originTile = new XMLData.Map.TilePos();
		_tileObject.originTile.gridPosX = cg.gridPosX;
		_tileObject.originTile.gridPosY = cg.gridPosY;
		return _tileObject;
	}
}*/
